﻿$(function($){
//	        $(document).ready(function () {
	   initAddEquDlg();
	   initLeftTree();
	   //////////////////toobar btn
	  $("#export").on("click",function(){
		
		 $("#lefgToolBar").jqxTreeGrid('exportData', 'xls');

   });
		
	$(".header_btn").jqxButton({width:100,height:30,theme:theme});
	$(".dlg_btn").jqxButton({width:50,height:20,theme:theme});
	//	$(".tool_btn").jqxButton({width:70,height:20,theme:theme});
});
function initLeftTree(){
       var newRowID=null;
                // prepare the data
                var source =
                {
                    dataType: "csv",
                    datafields: [
                        { name: 'id' ,type:"number"},
                        { name: 'parentid',type:"number" },
                        { name: 'text',type:"string" },
                        { name: 'propertyType',type:"string" },
						{ name: 'action',type:"string" }
                    ],
                    id: 'id',
                   // localdata: treeData,
				    url: 'testdata.csv',
					
                hierarchy:
                {
                    keyDataField: { name: 'id' },
                    parentDataField: { name: 'parentid' }
                },
				addRow: function (rowID, rowData, position, parentID, commit) {
                     // synchronize with the server - send insert command
                     // call commit with parameter true if the synchronization with the server is successful 
                     // and with parameter false if the synchronization failed.
                     // you can pass additional argument to the commit callback which represents the new ID if it is generated from a DB.
                     commit(true);
                    newRowID = rowID;
                 },
                 updateRow: function (rowID, rowData, commit) {
                     // synchronize with the server - send update command
                     // call commit with parameter true if the synchronization with the server is successful 
                     // and with parameter false if the synchronization failed.
                     commit(true);
                 },
                 deleteRow: function (rowID, commit) {
                     // synchronize with the server - send delete command
                     // call commit with parameter true if the synchronization with the server is successful 
                     // and with parameter false if the synchronization failed.
                     commit(true);
                 }

			
           };

                // create data adapter.
                var dataAdapter = new $.jqx.dataAdapter(source,{async:false});
                // perform Data Binding.
                // dataAdapter.dataBind();
                // get the tree items. The first parameter is the item's id. The second parameter is the parent item's id. The 'items' parameter represents 
                // the sub items collection name. Each jqxTree item has a 'label' property, but in the JSON data, we have a 'text' field. The last parameter 
                // specifies the mapping between the 'text' and 'label' fields.  
                var records = dataAdapter.getRecordsHierarchy('id', 'parentid', 'items', [{ name: 'text', map: 'label'}]);
                $('#lefgToolBar').jqxTreeGrid({ 
				source:source,
				 altrows: true,
				height: '679px',
				 width: '200px' ,
				 showheader:false,
				 
				 theme:theme,
				   columns: [
                  { text: 'Location Name', dataField: "text", align: 'center', width: '100%',       cellsRenderer : function(row, column, value, rowData){
					  
					    return rowData.text+row;
					  } 
					  }
				  /*,
                  { text: 'Population', dataField: "value", align: 'right', cellsAlign: 'right', width: '50%' }*/
                ]
				 
                  });//end treegrid

	   //$("#lefgToolBar").jqxTree( {height: '679px', width: '200px' ,theme:theme});
           $('#lefgToolBar').css('visibility', 'visible');
            // create context menu
           
 
            $("#lefgToolBar").on('contextmenu', function () {
                return false;
            });

            $("#lefgToolBar").on('rowClick', function (event) {
				  //顶层节点，不能删除，只有底层节点才能删除
                  // event args.
				var args = event.args;
				// row data.
				var row = args.row;
				// row key.
				var key = args.key;
				// original click event.
				var clickEvent = args.originalEvent;

				
                if (args.originalEvent.button == 2) {
                    var scrollTop = $(window).scrollTop();
                    var scrollLeft = $(window).scrollLeft();
					//alert( parseInt(event.args.originalEvent.clientY) + 5 + parseInt(scrollTop));
			      //   $("#context_menu").jqxMenu('open', 20, 20);  
				     var propertyType = $("#lefgToolBar").jqxTreeGrid('getCellValue', key, 'propertyType');  
					 switch(propertyType){
						 case"system_struts":
						 case"component_threeTransformer":
						 case"component_transformer":
						 case"component_bus":
						 case"component_lowbus":
						 case"component_lowbus_breaker":
						 case"component_converge":
						 case"component_gen":
						 case"component_inverter":
						 default:
						 }
                    contextMenu.jqxMenu('open', parseInt(event.args.originalEvent.clientX) + 5 + scrollLeft, parseInt(event.args.originalEvent.clientY) + 5 + scrollTop);
 
                    return false;
                }else
				{ 
				 
					    //获取当前选择的grid  select-measure字段的值
	                     var text = $("#lefgToolBar").jqxTreeGrid('getCellValue', key, 'text');
						 var value = $("#lefgToolBar").jqxTreeGrid('getCellValue', key, 'propertyType');
						
						 if(value&&value.indexOf("NaN")<0)//value作为子界面请求
						 {
						   // $("#dlg_body").html(text+"====="+value);
							  $("#dlg_body").load(value+".html"); 
						 }				 
				}
            });
			
			
			   $("#context_menu").on('itemclick', function (event) {
                var args = event.args;
                var selection = $("#lefgToolBar").jqxTreeGrid('getSelection');
                var rowid = selection[0].uid
                if ($.trim($(args).text()) == "添加设备") {
					
					$("#add_equ_dlg").jqxWindow("open");
					
					
                   // $("#lefgToolBar").jqxTreeGrid('beginRowEdit', rowid);
					//$("#lefgToolBar") .jqxTreeGrid('addRow', null, {text:"rrrrrrrrrr"+newRowID}, 'last', rowid);
					//var rows = $("#lefgToolBar").jqxTreeGrid('getRow', "rrrrrrrrrr");

					//alert(rows);
				//	$("#lefgToolBar") .jqxTreeGrid('addRow', null, {text:"rrr+"}, 'first', newRowID);
				//	$("#lefgToolBar") .jqxTreeGrid('addRow', null, {text:"rrrd+"}, 'first', newRowID);
				//	alert(newRowID);
                } else {
                    $("#lefgToolBar").jqxTreeGrid('deleteRow', rowid);
                }
 });
 		
  function isRightClick(event) {
            var rightclick;
                    if (!event) var event = window.event;
                    if (event.which) rightclick = (event.which == 3);
                    else if (event.button) rightclick = (event.button == 2);
                    return rightclick;
  }						

 		
} 
//返回tablesource
 function tableSource(url){
	  var source = {
        datatype : "xml",
        datafields : [{
            name : 'Desc',
            map : 'm\\:properties>d\\:Desc'
        }, {
            name : 'Feild',
            map : 'm\\:properties>d\\:Field'
        }, {
            name : 'DefaultValue',
            map : 'm\\:properties>d\\:DefaultValue'
        }, {
            name : 'DataType',
            map : 'm\\:properties>d\\:DataType' 
        } , {
            name : 'Enum',
            map : 'm\\:properties>d\\:EnumData' //在低版本中，xml的项必须存在，且不能为空，高版本中可以不存在，且能为空，所以在没有枚举量的xml项中补填N作为占位
        }],
        root : "content",
       // record : "content",
        id : 'm\\:properties>d\\:Field',
        url : url
	  }
	return source;	 
} 
//===============添加设备对话框
//系统默认添加--单母-单主变-低压母线-单集电线-单机组结构
//--系统结构》添加高压母线
//--母线》添加主变
//--主变》添加低压母线
//--低压母线》添加集电线
//
//
function initAddEquDlg(){
		
    var loadDlgContent=function(){

	var url = "table_xml/SystemTopology.xml";
    // prepare the data
	//加载配置文件
    var dataAdapter = new $.jqx.dataAdapter(tableSource(url), {
        loadComplete : function() {
            // get data records.
              var records = dataAdapter.records;
              var length = records.length;
              var propertyEdit=$('<table></table').appendTo("#add_equ_dlg_content");

		     for (var i = 0; i < length; i++) {
                var record = records[i];
				var propertyEditItem=$('<tr style="height:30px"></tr>').appendTo(propertyEdit);
				 var desc=$('<td style="width:80px" ></td>').html(record.Desc).appendTo(propertyEditItem);
				 var valitem=$("<td></td>").appendTo(propertyEditItem);
				//如果是枚举类型数据，获取枚举量，并形添加枚举值到droplist提供选择
			  if(record.DataType!="Enum")
				{   
				   
					var value=$('<input id="testinput" class="property_value" />').val(record.DefaultValue).appendTo(valitem);
			 
					value.jqxInput({
						placeHolder : "",
						height : 22,
						width : 95,
						minLength : 1
					});
  
			
				}else if(record.Enum){
				  
				     var combo=$('<div   class="property_comb" ></div>').attr("id",record.Feild).appendTo(valitem);
                     var combodata=[];
		
				     combo.jqxDropDownList({ source: combodata, autoDropDownHeight:true, displayMember: "text", valueMember: "value",theme:theme,selectedIndex: 0, width: 95, height: 22});  			  
				}
			}	
		}
	
	});

	 dataAdapter.dataBind();
	}
	 //添加设备对话框
	$("#add_equ_dlg").jqxWindow({
						width : 200,
						height:230,
						title :"添加设备",
						theme : theme,
						resizable : false,
						isModal : true,
						autoOpen : false,
						cancelButton : $("#Cancel"),
						modalOpacity : 0.01,
						initContent : loadDlgContent
	});
 };	